<template>
  <view class="my-fees-page">
    <!-- 物业费记录列表 -->
    <scroll-view 
      scroll-y="true" 
      class="fees-scroll" 
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <view class="fees-content">
        <!-- 物业费记录卡片 -->
        <view 
          v-for="item in feesList" 
          :key="item.id"
          class="fee-card"
          @click="goToFeeDetail(item)"
        >
          <!-- 卡片头部 -->
          <view class="card-header">
            <view class="header-left">
              <text class="fee-title">{{ item.feeName || '物业费' }}</text>
              <u-tag 
                :text="getStatusText(item.paymentStatus)" 
                :type="getStatusType(item.paymentStatus)" 
                size="mini"
                class="status-tag"
              />
            </view>
            <text class="fee-time">{{ formatTime(item.createTime) }}</text>
          </view>
          
          <!-- 卡片内容 -->
          <view class="card-content">
            <view class="content-item">
              <u-icon name="map" size="14" color="#666" class="item-icon"></u-icon>
              <text class="item-text">{{ item.householdAddress || '暂无地址信息' }}</text>
            </view>
            <view class="content-item">
              <u-icon name="calendar" size="14" color="#666" class="item-icon"></u-icon>
              <text class="item-text">{{ item.billingPeriod || '暂无计费周期' }}</text>
            </view>
            <view class="content-item">
              <u-icon name="rmb-circle" size="14" color="#666" class="item-icon"></u-icon>
              <text class="item-text">金额：¥{{ formatAmount(item.amount) }}</text>
            </view>
            <view class="content-item" v-if="item.paymentAmount > 0">
              <u-icon name="checkmark-circle" size="14" color="#666" class="item-icon"></u-icon>
              <text class="item-text">已缴：¥{{ formatAmount(item.paymentAmount) }}</text>
            </view>
          </view>
          
          <!-- 卡片底部 -->
          <view class="card-footer">
            <view class="progress-info">
              <text class="progress-text">{{ getProgressText(item.paymentStatus) }}</text>
              <view class="progress-bar">
                <view 
                  class="progress-fill"
                  :style="{ 
                    width: getProgressPercentage(item.paymentStatus) + '%',
                    backgroundColor: getStatusColor(item.paymentStatus)
                  }"
                ></view>
              </view>
            </view>
            
            <view class="action-buttons">
              <u-button 
                type="primary" 
                text="详情"
                size="mini"
                @click.stop="goToFeeDetail(item)"
                class="action-btn"
              />
            </view>
          </view>
        </view>
        
        <!-- 空状态 -->
        <view v-if="feesList.length === 0 && !loading" class="empty-state">
          <u-empty 
            text="暂无物业费记录" 
            icon="list"
            mode="list"
          />
        </view>
        
        <!-- 加载更多提示 -->
        <view v-if="feesList.length > 0" class="load-more-tip">
          <text v-if="loading" class="tip-text">加载中...</text>
          <text v-else-if="hasMore" class="tip-text">上拉加载更多</text>
          <text v-else class="tip-text">没有更多数据了</text>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
/**
 * 我的物业费页面
 * @author Wu.Liang
 * @date 2025-01-30
 * @version 1.0.0 - 物业费查询功能实现
 */

import { ref, onMounted } from 'vue'
import { propertyFeeApi } from '@/api/property'

// ==================== 响应式数据定义 ====================

// 物业费记录列表
const feesList = ref([])

// 加载状态
const loading = ref(false)
const refreshing = ref(false)
const hasMore = ref(true)

// 分页参数
const currentPage = ref(1)
const pageSize = ref(20)

// ==================== 方法定义 ====================

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '未缴费',
    1: '已缴费',
    2: '逾期',
    3: '部分缴费'
  }
  return statusMap[status] || '未知状态'
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    0: 'warning',
    1: 'success',
    2: 'error',
    3: 'info'
  }
  return typeMap[status] || 'info'
}

// 获取状态颜色
const getStatusColor = (status) => {
  const colorMap = {
    0: '#E6A23C', // 未缴费 - 橙色
    1: '#67C23A', // 已缴费 - 绿色
    2: '#F56C6C', // 逾期 - 红色
    3: '#409EFF'  // 部分缴费 - 蓝色
  }
  return colorMap[status] || '#909399'
}

// 获取进度文本
const getProgressText = (status) => {
  const progressMap = {
    0: '等待缴费',
    1: '缴费完成',
    2: '已逾期',
    3: '部分缴费'
  }
  return progressMap[status] || '等待缴费'
}

// 获取进度百分比
const getProgressPercentage = (status) => {
  const percentageMap = {
    0: 20,
    1: 100,
    2: 0,
    3: 60
  }
  return percentageMap[status] || 20
}

// 格式化金额
const formatAmount = (amount) => {
  if (!amount && amount !== 0) return '0.00'
  return Number(amount).toFixed(2)
}

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return ''
  
  try {
    const date = new Date(timeStr)
    const now = new Date()
    const diff = now - date
    
    // 小于1分钟
    if (diff < 60000) return '刚刚'
    
    // 小于1小时
    if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
    
    // 小于24小时
    if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
    
    // 小于30天
    if (diff < 2592000000) return `${Math.floor(diff / 86400000)}天前`
    
    // 超过30天，显示具体日期
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    })
  } catch (error) {
    // 开发环境记录错误日志
    if (process.env.NODE_ENV === 'development') {
      console.error('时间格式化失败:', error)
    }
    return ''
  }
}

// 加载物业费列表
const loadFeesList = async () => {
  if (loading.value || !hasMore.value) return
  
  try {
    loading.value = true
    
    // 显示加载提示
    if (currentPage.value === 1) {
      uni.showLoading({
        title: '加载中...',
        mask: true
      })
    }
    
    const params = {
      current: currentPage.value,
      size: pageSize.value
    }
    
    // 开发环境显示调试信息
    if (process.env.NODE_ENV === 'development') {
      console.log('加载物业费列表参数:', params)
    }
    
    const response = await propertyFeeApi.getMyPropertyFees(params)
    
    if (response.success && response.data) {
      const { records, total, current, pages } = response.data
      
      if (currentPage.value === 1) {
        feesList.value = records || []
      } else {
        feesList.value.push(...(records || []))
      }
      
      hasMore.value = current < pages
      currentPage.value = current + 1
      
      // 开发环境显示调试信息
      if (process.env.NODE_ENV === 'development') {
        console.log('物业费列表加载成功:', {
          total,
          current,
          pages,
          recordsCount: records?.length || 0,
          hasMore: hasMore.value
        })
      }
    } else {
      // 优先展示后端返回的提示消息，只有在后端没有返回合适的提示消息时才能使用前端自定义的提示消息
      const errorMessage = response.message || response.msg || '加载失败'
      uni.showToast({
        title: errorMessage,
        icon: 'none'
      })
    }
  } catch (error) {
    // 开发环境记录错误日志
    if (process.env.NODE_ENV === 'development') {
      console.error('加载物业费列表失败:', error)
    }
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none'
    })
  } finally {
    loading.value = false
    refreshing.value = false
    uni.hideLoading()
  }
}

// 下拉刷新
const onRefresh = () => {
  refreshing.value = true
  currentPage.value = 1
  hasMore.value = true
  loadFeesList()
}

// 上拉加载更多
const loadMore = () => {
  if (!loading.value && hasMore.value) {
    loadFeesList()
  }
}

// 跳转到物业费详情
const goToFeeDetail = (item) => {
  uni.navigateTo({
    url: `/pages/property/fee-detail?id=${item.id}`
  })
}



// ==================== 生命周期 ====================

onMounted(() => {
  // 加载物业费列表
  loadFeesList()
})
</script>

<style lang="scss" scoped>
/* 页面容器 */
.my-fees-page {
  width: 100%;
  height: 100vh;
  background-color: #f8f9fa;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* 滚动视图 */
.fees-scroll {
  flex: 1;
  width: 100%;
  overflow-y: auto;
  min-height: 0;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* 内容区域 */
.fees-content {
  width: 100%;
  padding: 16px 12px 12px 12px;
  box-sizing: border-box;
  margin: 0;
}

/* 物业费记录卡片 */
.fee-card {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  margin: 8px 0;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  width: 100%;
  box-sizing: border-box;
  
  &:active {
    transform: scale(0.98);
    box-shadow: 0 1px 6px rgba(0, 0, 0, 0.15);
  }
  
  &:first-child {
    margin-top: 0;
  }
  
  &:last-child {
    margin-bottom: 12px;
  }
}

/* 卡片头部 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
  
  .header-left {
    display: flex;
    align-items: flex-start;
    gap: 8px;
    flex: 1;
    margin-right: 12px;
  }
  
  .fee-title {
    font-size: 16px;
    font-weight: 600;
    color: #2c3e50;
    line-height: 1.4;
    flex: 1;
    word-break: break-all;
  }
  
  .status-tag {
    flex-shrink: 0;
  }
  
  .fee-time {
    font-size: 12px;
    color: #95a5a6;
    flex-shrink: 0;
    white-space: nowrap;
  }
}

/* 卡片内容 */
.card-content {
  margin-bottom: 16px;
  
  .content-item {
    display: flex;
    align-items: flex-start;
    margin-bottom: 8px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .item-icon {
      margin-right: 8px;
      margin-top: 2px;
      flex-shrink: 0;
    }
    
    .item-text {
      font-size: 14px;
      color: #5a6c7d;
      line-height: 1.5;
      flex: 1;
      word-break: break-all;
    }
  }
}

/* 卡片底部 */
.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .progress-info {
    flex: 1;
    margin-right: 16px;
    
    .progress-text {
      font-size: 12px;
      color: #7f8c8d;
      margin-bottom: 6px;
      display: block;
    }
    
    .progress-bar {
      width: 100%;
      height: 4px;
      background-color: #ecf0f1;
      border-radius: 2px;
      overflow: hidden;
    }
    
    .progress-fill {
      height: 100%;
      border-radius: 2px;
      transition: width 0.3s ease;
    }
  }
  
  .action-buttons {
    display: flex;
    gap: 8px;
    flex-shrink: 0;
  }
  
  .action-btn {
    min-width: 60px;
  }
}

/* 空状态 */
.empty-state {
  padding: 60px 20px;
  text-align: center;
}

/* 加载更多提示 */
.load-more-tip {
  text-align: center;
  padding: 20px 0;
  
  .tip-text {
    font-size: 12px;
    color: #95a5a6;
  }
}

/* 响应式适配 */
@media screen and (max-width: 375px) {
  .fees-content {
    padding: 0 8px;
  }
  
  .fee-card {
    padding: 12px;
    margin: 6px 0;
    
    &:first-child {
      margin-top: 8px;
    }
    
    &:last-child {
      margin-bottom: 8px;
    }
  }
  
  .card-header .fee-title {
    font-size: 15px;
  }
  
  .card-content .content-item .item-text {
    font-size: 13px;
  }
}

@media screen and (min-width: 414px) {
  .fees-content {
    padding: 0 16px;
  }
  
  .fee-card {
    margin: 10px 0;
    
    &:first-child {
      margin-top: 16px;
    }
    
    &:last-child {
      margin-bottom: 16px;
    }
  }
  
  .card-header .fee-title {
    font-size: 17px;
  }
  
  .card-content .content-item .item-text {
    font-size: 15px;
  }
}

@media screen and (orientation: landscape) {
  .my-fees-page {
    height: 100vh;
  }
  
  .fees-content {
    padding: 0 12px;
  }
  
  .fee-card {
    margin: 6px 0;
    
    &:first-child {
      margin-top: 8px;
    }
    
    &:last-child {
      margin-bottom: 8px;
    }
  }
  
  .card-header .fee-title {
    font-size: 14px;
  }
  
  .card-content .content-item .item-text {
    font-size: 12px;
  }
}
</style>
